﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ServerSocket {
    public class StateObject {
        public Socket workSocket;
        public const int BufferSize = 1024;
        public byte[] buffer = new byte[BufferSize];
    }
    class ServerSocket {
        public static string ip = "192.168.0.104";
        public static int port = 8081;
        public static ManualResetEvent allDone = new ManualResetEvent (false);
        public static void StartListen () {
            IPAddress iPAddress = IPAddress.Parse (ip);
            IPEndPoint ipointend = new IPEndPoint (iPAddress, port);
            Socket listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try {
                listener.Bind (ipointend);
                listener.Listen (100);
                while (true) {
                    allDone.Reset ();
                    listener.BeginAccept (new AsyncCallback (AcceptCallback), listener);
                    Console.WriteLine ("等待连接");
                    allDone.WaitOne ();
                }
            } catch (System.Exception e) {
                Console.WriteLine (e);
                throw;
            }

        }
        private static void AcceptCallback (IAsyncResult ar) {
            allDone.Set ();
            Socket listener = (Socket) ar.AsyncState;
            Socket handler = listener.EndAccept (ar);
            Console.WriteLine ("一个客户端连接进来了" + handler.RemoteEndPoint);
            StateObject state = new StateObject ();
            state.workSocket = handler;
            handler.BeginReceive (state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback (ReceiveCallback), state);
        }
        private static void ReceiveCallback (IAsyncResult ar) {
            try {
                string content = String.Empty;
                StateObject state = (StateObject) ar.AsyncState;
                Socket handler = state.workSocket;
                SocketError error;
                int bytesread = handler.EndReceive (ar, out error);
                if (bytesread > 0) {
                    content = Encoding.UTF8.GetString (state.buffer, 0, bytesread);
                    Console.WriteLine ("接收到消息：" + content + "来自于：" + handler.LocalEndPoint);
                } else {
                    Console.WriteLine ("没有接受到任何消息"+error.ToString ());
                }

                // StateObject newstate = new StateObject ();
                // newstate.workSocket = handler;
                 if (handler.Connected == false) {
                     Console.WriteLine ("客户端掉线");
                     return;
                 }
                handler.BeginReceive (state.buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
            } catch (System.Exception e) {
                Console.WriteLine (e);
                // throw;
            }

        }
    }
    class Program {
        static void Main (string[] args) {
            ServerSocket.StartListen ();
        }
    }
}